from datetime import datetime

import pytz
from flask import url_for
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import Mapped, mapped_column, relationship

from auth.models import User
from extensions import db


def now_utc() -> datetime:
    return datetime.now(pytz.timezone('Asia/Shanghai'))


class Post(db.Model):
    __tablename__ = "test_blog"
    id: Mapped[int] = mapped_column(primary_key=True)
    author_id: Mapped[int] = mapped_column(ForeignKey("test_user.id"))
    created: Mapped[datetime] = mapped_column(default=now_utc)
    title: Mapped[str] = mapped_column(String(30))
    body: Mapped[str] = mapped_column(String(500))

    # User object backed by author_id
    # lazy="joined" means the user is returned with the post in one query
    author: Mapped[User] = relationship(lazy="joined", back_populates="posts")

    @property
    def update_url(self) -> str:
        return url_for("blog.update", id=self.id)

    @property
    def delete_url(self) -> str:
        return url_for("blog.delete", id=self.id)
